import { mapState } from 'vuex'
import { userModule } from '@/store/modules/user'

import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import { subsidyServices } from '@/common/services/subsidy'
import { TableMixin } from '@/mixin'

@Component
export class RosterMixins extends Mixins(TableMixin) {
  @Prop({
    type: String
  })
  public currentAreaId!: string

  public isShowIndexColumn = true

  public isUsed = 0
  public batchIsUsed = false

  public batchIsUsedLoading = false;

  public async getData() {
    this.isInitSelected = false
    const res = await this.getTableList()
    this.selectedRowKeys = this.tableData
      .filter(item => +item.is_used === 1)
      .map(item => userModule.isLarge ? item.big_mb_id : item.iid)

    // 已选择用户数据
    const totalData = this.tableData[0]
    if (totalData && totalData.is_used_num) {
      this.isUsed = totalData.is_used_num
    }

    // 未设置补贴金额提示
    const currentPrice = totalData ? totalData.pay_price : 0
    if (totalData && (!currentPrice || currentPrice <= 0)) {
      this.$warning({
        content: '该区县未设置补贴标准，无法计算补贴金额！请联系该区县级管理员尽快设置...',
        centered: true
      })
    }
    this.$nextTick(() => {
      this.isInitSelected = true
    })
  }


  @Watch('batchIsUsed')
  public handlerChangeBatchIsUsed(val: boolean) {
    this.batchIsUsedLoading = true
    subsidyServices
      .setSubsidyStatus({
        is_area: true,
        s_a_id: this.currentAreaId,
        is_used: val ? '1' : '2'
      })
      .then(() => {
        this.getData()
        this.$message.success('补贴状态更新成功')
      }).finally(() => {
        this.batchIsUsedLoading = false
      })
  }

  public isInitSelected = false
  @Watch('selectedRowKeys')
  public handlerChangeSelectedRowKeys(newVals: string[], oldVals: string[]) {
    if (!this.isInitSelected) return
    let isUsed = 1
    let ids: string[] = []
    if (newVals.length - oldVals.length > 0) {
      // 添加
      isUsed = 1
      ids = newVals.filter(str => !oldVals.includes(str))
    } else {
      // 移除
      isUsed = 2
      ids = oldVals.filter(str => !newVals.includes(str))
    }
    if (!ids.length) return
    const params = userModule.isLarge ? {big_mb_id: ids.join(',')} : {iid: ids.join(',')}
    subsidyServices
      .setSubsidyStatus({
        ...params,
        is_used: `${isUsed}`
      })
      .then(() => {
        this.getData()
        this.$message.success('补贴状态更新成功')
      })
  }
}
